package snowflakeid.v2;

/**
 * ChatGPT 生成
 *
 * @author licong
 * @date 2022-12-21 22:00
 */
public class SnowflakeIdGenerator {
    // 起始的时间戳
    private final static long START_TIMESTAMP = 1480166465631L;
    // 机器id所占的位数
    private final static long WORKER_ID_BITS = 5L;
    // 数据中心id所占的位数
    private final static long DATA_CENTER_ID_BITS = 5L;
    // 支持的最大机器id(十进制)，结果是31
    private final static long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 支持的最大数据中心id(十进制)，结果是31
    private final static long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    // 序列在id中占的位数
    private final static long SEQUENCE_BITS = 12L;
    // 机器ID的偏移量(12)
    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
    // 数据中心ID的偏移量(12+5)
    private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    // 时间戳的偏移量(5+5+12)
    private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS;
    // 生成序列的掩码(4095)，这里为了方便演示，去掉了最后的四位
    private final static long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
    // 工作机器ID(0~31)
    private long workerId;
    //数据中心ID(031)
    private long dataCenterId;
    // 毫秒内序列(04095)
    private long sequence = 0L;
    // 上次生成ID的时间戳
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(long workerId, long dataCenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", MAX_DATA_CENTER_ID));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    public synchronized long nextId() {
        long timestamp = currentTime();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = nextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) | (dataCenterId << DATA_CENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT) | sequence;
    }

    protected long currentTime() {
        return System.currentTimeMillis();
    }

    private long nextMillis(long lastTimestamp) {
        long timestamp = currentTime();
        while (timestamp <= lastTimestamp) {
            timestamp = currentTime();
        }
        return timestamp;
    }

    /**
     * workerId：工作机器 ID，用于区分不同的机器。
     * dataCenterId：数据中心 ID，用于区分不同的数据中心。
     * sequence：序列号，每次生成 ID 时自增。
     * lastTimestamp：上一次生成 ID 的时间戳。
     */
    public static void main(String[] args) {
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        for (int i = 0; i < 100; i++) {
            long id = idGenerator.nextId();
            System.out.println(id);
        }
    }
}
